package com.hue.netty.day02.two;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import java.time.LocalDateTime;

/*
    处理文本帧的处理器
 */
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("接收到客户端的消息:" + msg.text());
        //接收到消息后给客户端提示
        ctx.writeAndFlush(new TextWebSocketFrame("[" + LocalDateTime.now() + "]服务器接收到消息:" + msg.text()));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //id是唯一值，longText唯一，shortText不唯一
        System.out.println("handlerAdded--"+ctx.channel().id().asLongText());
        System.out.println("handlerAdded--"+ctx.channel().id().asShortText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved--"+ctx.channel().id().asLongText());
        System.out.println("handlerRemoved--"+ctx.channel().id().asShortText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("客户端下线...");
        ctx.close();
    }
}
